package br.com.naybee.framework.client.freemarker;

import java.util.List;

import freemarker.template.SimpleScalar;
import freemarker.template.SimpleSequence;
import freemarker.template.TemplateMethodModelEx;
import freemarker.template.TemplateModelException;

public class FreeMarkerFunctions {

	public static class Eq implements TemplateMethodModelEx {
		public static final String NAME = "eq";

		public Object exec(@SuppressWarnings("rawtypes") List args) throws TemplateModelException {
			if (args.size() != 2) {
				throw new TemplateModelException("Wrong arguments");
			}
			Object p1 = args.get(0);
			Object p2 = args.get(1);

			if (p1 == p2) {
				return true;
			} else if (p1 != null && p2 != null) {
				return p1.toString().equals(p2.toString());
			} else {
				return false;
			}
		}
	}

	public static class Empty implements TemplateMethodModelEx {
		public static final String NAME = "empty";

		public Object exec(@SuppressWarnings("rawtypes") List args) throws TemplateModelException {
			if (args.size() != 1) {
				throw new TemplateModelException("Wrong arguments");
			}

			Object p1 = args.get(0);

			if (p1 == null) {
				return true;
			} else if (p1 instanceof SimpleScalar && ((SimpleScalar) p1).getAsString().isEmpty()) {
				return true;
			} else if (p1 instanceof SimpleSequence && ((SimpleSequence) p1).size() == 0) {
				return true;
			} else {
				return false;
			}
		}
	}

	public static class Exists implements TemplateMethodModelEx {
		public static final String NAME = "exists";

		public Object exec(@SuppressWarnings("rawtypes") List args) throws TemplateModelException {
			if (args.size() != 2) {
				throw new TemplateModelException("Wrong arguments");
			}

			Object p1 = args.get(0);
			Object p2 = args.get(1);

			if (!(p1 instanceof SimpleSequence)) {
				throw new TemplateModelException("Wrong arguments");
			} else {
				SimpleSequence ss = (SimpleSequence) p1;
				List<?> h = ss.toList();

				if (p2 != null) {
					if (h.contains(p2.toString())) {
						return true;
					}
				}

				return false;
			}

		}
	}

}
